package com.topisv.tms.web.lpn;

import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.lpn.LPN;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.lpn.LPNService;
import com.topisv.tms.service.lpn.LpnStorageService;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.web.base.BaseDataTableController;

import net.sf.json.JSONObject;
@Controller
@RequestMapping(value = "/v2_lpn")
public class LPNController extends BaseDataTableController{
	private static final Logger log = LoggerFactory.getLogger(LPNController.class);
	
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private LPNService lpnService;
	@Autowired
	private LpnStorageService lpnStorageService;

	@RequestMapping(value = "v2_show")
	public String list(Model model) {
		ShiroUser curUser = getShiroUser();
		List<AreaGroup> warehouseList = null;
		if (StatusEnums.user_type_customer.getStatus().equals(curUser.userType)) {
			warehouseList = areaGroupService.loadAreaGroupByAuthority(curUser, curUser.customerCode);
		} else if (StatusEnums.user_type_paiu.getStatus().equals(curUser.userType)) {
			warehouseList = areaGroupService.findByAreaGroups(curUser.areagroups);
		}
		model.addAttribute("warehouseList", warehouseList);
		return "lpn/LPNList";
	}
	@RequestMapping(value = "queryLPN")
	public void queryLPN(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response) {
		try {
			// 客户端参数
			QueryParamHolder paramHolder = collectParam(paramJson);
			Page<LPN> page =this.lpnService.loadPageByParam(paramHolder.getSearchParams(),paramHolder.getCurPage(), paramHolder.getPageSize());
			// 封装查询结果
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			log.error("error",e);
		}
	}
	
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		ShiroUser curUser = getShiroUser();
		List<AreaGroup> warehouseList = null;
		if (StatusEnums.user_type_customer.getStatus().equals(curUser.userType)) {
			warehouseList = areaGroupService.loadAreaGroupByAuthority(curUser, curUser.customerCode);
		} else if (StatusEnums.user_type_paiu.getStatus().equals(curUser.userType)) {
			warehouseList = areaGroupService.findByAreaGroups(curUser.areagroups);
		}
		model.addAttribute("warehouseList", warehouseList);
		model.addAttribute("lpn", new LPN());
		model.addAttribute("action", "create");
		return "lpn/LPNForm";
	}
	@RequestMapping(value = "create", method = RequestMethod.POST)
	public void create(ServletRequest request,HttpServletResponse response) {
		ShiroUser user=getShiroUser();
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			LPN lpnNew=new LPN();
			String lpnType=request.getParameter("lpnType");
			lpnNew.setWarehouseCode(request.getParameter("warehouseCode"));
			if(request.getParameter("LPN").toUpperCase().indexOf(lpnNew.getWarehouseCode())>-1){
				lpnNew.setLpnNo(request.getParameter("LPN").toUpperCase());
			}else{
				lpnNew.setLpnNo(new StringBuilder().append(lpnNew.getWarehouseCode())
						.append(request.getParameter("LPN").toUpperCase()).toString());
			}
			lpnNew.setStatus("0");
			lpnNew.setStorageType(lpnType);
			lpnNew.setStorageTable(StringUtils.equals(lpnType, "0")? "lpn":"pallte");
			lpnNew.setOrderNo("");
			lpnNew.setCreateTime(new Date());
			lpnNew.setLastModifyTime(new Date());
			List<LPN> checkLPN=this.lpnService.checkLPN(lpnNew.getWarehouseCode(),lpnNew.getLpnNo());
			if(checkLPN.size()==0){
				lpnService.save(lpnNew);
				json.put("status","success");
				json.put("content","创建成功");
			}else{
				json.put("status","error");
				json.put("content","LPN重复");
			}
				
		} catch (Exception e) {
			log.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());		
		}
		out.print(json.toString());
	}
	
	@RequestMapping(value = "deleteLPN",method = RequestMethod.POST)
	public void confirmReceive(ServletRequest request,HttpServletResponse response) {
			JSONObject json = null;
			PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			String msg="";
			Long id=Long.valueOf(request.getParameter("id"));
			LPN lpn=this.lpnService.findLPNById(id);
			if(lpn.getStatus().equals("0")){
				lpnService.deleteLPN(lpn);
				json.put("status","success");
				json.put("content","删除成功");
			}else{
				json.put("status","error");
				json.put("content","使用中不能删除");
			}
		} catch (Exception e) {
			log.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());
		}
		out.print(json.toString());
	}
	
	private String getValue(HSSFCell hssfCell) {
       if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(hssfCell.getBooleanCellValue());
       } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            return String.valueOf((int)hssfCell.getNumericCellValue());
       } else {
           return String.valueOf(hssfCell.getStringCellValue());
       }
    }

	private String getValue(XSSFCell xssfRow) {
         if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
           return String.valueOf(xssfRow.getBooleanCellValue());
	     } else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
	            return String.valueOf((int)xssfRow.getNumericCellValue());
	     } else {
	           return String.valueOf(xssfRow.getStringCellValue());
	      }
    }

	/**
	 * 导入Excel
	 * @param model
	 * @param request
	 * @param redirectAttributes
	 */
	@RequestMapping(value = "importExcel/{file_lpnType}")
	public String importExcel(Model model,@PathVariable(value = "file_lpnType") String lpnType,
			ServletRequest request, RedirectAttributes redirectAttributes){	
		HttpServletRequest httpRequest = null;
		DiskFileItemFactory factory = null;
		ServletFileUpload upload = null;
		List<FileItem> items = null;
		Workbook rwb = null;
		List<LPN> lpnList=new ArrayList<LPN>();
		try{
			httpRequest = (HttpServletRequest) request;
			httpRequest.setCharacterEncoding("UTF-8");
			factory = new DiskFileItemFactory();
			upload = new ServletFileUpload(factory);
			items = upload.parseRequest(httpRequest);
			
			Iterator<FileItem> itr = items.iterator();
			int uploadFileCount=0;
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (!item.isFormField()) {// 非表单字段就是上传处理文件
					
					if (item.getName() != null && !item.getName().equals("")) {
						uploadFileCount++;
						// 获取Excel文件对象
						InputStream stream = item.getInputStream();
						if (item.getName().endsWith(".xls")) {// 解析xls
							rwb = new HSSFWorkbook(stream);
							Sheet sheet = rwb.getSheetAt(0);
							 for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
								 HSSFRow hssfRow = (HSSFRow) sheet.getRow(rowNum);
								 if (hssfRow != null) {
									LPN lpn=new LPN();
									HSSFCell warehouseCode=hssfRow.getCell(0);
									if (warehouseCode == null || warehouseCode.getCellType() == HSSFCell.CELL_TYPE_BLANK) {    
										continue;
									}
									HSSFCell lpnNo=hssfRow.getCell(1);
									if (lpnNo == null || lpnNo.getCellType() == HSSFCell.CELL_TYPE_BLANK) {    
										continue;
									}
									lpn.setWarehouseCode(getValue(warehouseCode).trim().toUpperCase());
									if(getValue(lpnNo).trim().toUpperCase().indexOf(lpn.getWarehouseCode())>-1){
										lpn.setLpnNo(getValue(lpnNo).trim().toUpperCase());
									}else{
										lpn.setLpnNo(new StringBuilder().append(lpn.getWarehouseCode())
												.append(getValue(lpnNo).trim().toUpperCase()).toString());
									}
									lpn.setStatus("0");
									lpn.setOrderNo("");
									lpn.setStorageType(lpnType);
									lpn.setStorageTable(StringUtils.equals(lpnType, "0")? "lpn":"pallte");
									lpn.setCreateTime(new Date());
									lpn.setLastModifyTime(new Date());
									lpnList.add(lpn);
								 }
							}
							
						} else if (item.getName().endsWith(".xlsx")) {// 解析xlsx
							rwb = new XSSFWorkbook(stream);
							XSSFSheet sheet = (XSSFSheet) rwb.getSheetAt(0);
							for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
								XSSFRow xssfRow=sheet.getRow(rowNum);
								if (xssfRow != null) {
									LPN lpn=new LPN();
									XSSFCell warehouseCode=xssfRow.getCell(0);
									if (warehouseCode == null || warehouseCode.getCellType() == HSSFCell.CELL_TYPE_BLANK) {    
										continue;
									}
									XSSFCell lpnNo=xssfRow.getCell(1);
									if (lpnNo == null || lpnNo.getCellType() == HSSFCell.CELL_TYPE_BLANK) {    
										continue;
									}
									lpn.setWarehouseCode(getValue(warehouseCode).trim().toUpperCase());
									if(getValue(lpnNo).trim().toUpperCase().indexOf(lpn.getWarehouseCode())>-1){
										lpn.setLpnNo(getValue(lpnNo).trim().toUpperCase());
									}else{
										lpn.setLpnNo(new StringBuilder().append(lpn.getWarehouseCode())
												.append(getValue(lpnNo).trim().toUpperCase()).toString());
									}
									lpn.setStatus("0");
									lpn.setOrderNo("");
									lpn.setStorageType(lpnType);
									lpn.setStorageTable(StringUtils.equals(lpnType, "0")? "lpn":"pallte");
									lpn.setCreateTime(new Date());
									lpn.setLastModifyTime(new Date());
									lpnList.add(lpn);
								}
							}
							
						}
						
						if(lpnList.size()>0){
							Map<String, List<LPN>> mapLPNs=new HashMap<String, List<LPN>>();
							mapLPNs.put("exception", new ArrayList<LPN>());//导入失败的LPN
							mapLPNs.put("normal", new ArrayList<LPN>());//导入成功的LPN
							mapLPNs.put("repeat", new ArrayList<LPN>());//重复LPN
							for(LPN lpn:lpnList){
								AreaGroup areaGroup=areaGroupService.findByGroupCode(lpn.getWarehouseCode());
								if(areaGroup==null){
									mapLPNs.get("exception").add(lpn);
									continue;
								}
								List<LPN> checkLPN=lpnService.checkLPN(lpn.getWarehouseCode(),lpn.getLpnNo());
								if(checkLPN.size()==0){
									try{
										lpnService.save(lpn);
										mapLPNs.get("normal").add(lpn);
									}catch(Exception e){
										mapLPNs.get("exception").add(lpn);
									}
								}else{
									mapLPNs.get("repeat").add(lpn);
								}
							}
							model.addAttribute("normal", mapLPNs.get("normal"));
							model.addAttribute("exception", mapLPNs.get("exception"));
							model.addAttribute("repeat", mapLPNs.get("repeat"));
							model.addAttribute("message", "订单导入成功");
							model.addAttribute("status", "1");
							model.addAttribute("number",lpnList.size());
							log.info("导入成功");
						}else{
							uploadFileCount--; // 文件没有数据
						}
					} else {
						log.error("LPN导入文件名为空");
					}
					
				}
				if(uploadFileCount <=0){
					model.addAttribute("status", "2");
					model.addAttribute("message", "没有上传订单文件或订单文件无效或无数据");
					log.error("没有上传订单文件或订单文件无效或无数据");
				}
			}
		}catch(Exception e){
			model.addAttribute("status", "2");
			model.addAttribute("message", "订单导入数据失败");
			log.error("订单导入失败",e);
		}
		return "lpn/leadLPNValue";
	}
}
